<template>
  <div class="trademark">
    <el-card>
      <div slot="header">
        <el-button
          size="small"
          type="primary"
          icon="el-icon-plus"
          @click="addOreditTrademark(null)"
          >添加</el-button
        >
      </div>
      <el-table border :data="pagelist" v-loading="loading">
        <el-table-column
          type="index"
          label="序号"
          width="80px"
          align="center"
        ></el-table-column>
        <el-table-column prop="tmName" label="品牌名称"></el-table-column>
        <el-table-column label="品牌LOGO">
          <template v-slot="{ row }">
            <el-image :src="row.logoUrl" style="width: 100px; "></el-image>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template v-slot="{ row }">
            <el-button
              style="margin-right: 10px;"
              size="mini"
              type="warning"
              icon="el-icon-edit"
              title="修改"
              @click="addOreditTrademark(row)"
            ></el-button>

            <el-popconfirm
              :title="`确定删除吗？`"
              @onConfirm="removeTrademark(row.id)"
            >
              <el-button
                slot="reference"
                size="mini"
                type="danger"
                title="删除"
                icon="el-icon-delete"
              ></el-button>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="page"
        :page-sizes="[3, 6, 9]"
        background
        :page-size="limit"
        layout="prev, pager, next, jumper,->,sizes,total"
        :total="total"
        style="margin-top: 20px;"
      >
      </el-pagination>
    </el-card>

    <el-dialog :title="title" top="0px" :visible="isShowDialog" width="50%">
      <el-form
        label-width="120px"
        :rules="rules"
        ref="ruleForm"
        :model="trademark"
      >
        <el-form-item label="品牌名称" prop="logName">
          <el-input
            placeholder="请输入品牌名称"
            v-model="trademark.logName"
          ></el-input>
        </el-form-item>
        <el-form-item label="品牌LOGO" prop="logUrl">
          <el-upload
            class="avatar-uploader"
            :action="`${VUE_APP_BASE_API}/admin/product/fileUpload`"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img
              v-if="trademark.logUrl"
              :src="trademark.logUrl"
              class="avatar "
            />
            <i v-else class="el-icon-plus el-upload avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="deletetrademark">取 消</el-button>
        <el-button type="primary" @click="saveTrademark">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  getTrademarkPageListApi,
  updateTrademarkApi,
  saveTrademarkApi,
  removeTrademarkApi
} from "@/api/product/trademark.js";

export default {
  naem: "Trademark",
  data() {
    return {
      // 当前页
      page: 1,
      // 每页条数
      limit: 3,
      // 分页列表
      pagelist: [],
      //总条数
      total: 0,

      // 控制显示Dialog
      isShowDialog: false,
      // 修改或者添加的标题
      title: "",

      // 表单的内容
      trademark: {
        logName: "",
        logUrl: ""
      },
      // 数据的id
      logId: null,

      // 发发请求的前面的统一名称
      VUE_APP_BASE_API: process.env.VUE_APP_BASE_API,

      // 加载
      loading: false,

      // 表单校验的规则
      rules: {
        logName: [
          { required: true, message: "请输入LOGO名称", trigger: "blur" },
          { min: 3, max: 9, message: "长度在 3 到 9个字符", trigger: "change" }
        ],
        logUrl: { required: true, message: "请添加图片", trigger: "blur" }
      }
    };
  },
  mounted() {
    // 初始化请求
    this.getPageList();
  },
  methods: {
    // 获取分页列表
    async getPageList() {
      this.loading = true;
      const result = await getTrademarkPageListApi(this.page, this.limit);
      this.pagelist = result.data.records;
      this.total = result.data.total;
      this.loading = false;
    },

    // 改变每页条数时触发的
    handleSizeChange(val) {
      this.limit = val;
      this.getPageList();
    },
    // 改变页码时触发的
    handleCurrentChange(val) {
      this.page = val;
      this.getPageList();
    },

    // 添加或者修改
    async addOreditTrademark(row) {
      this.cleardate();
      // 如果传过来的是一个对象 代表是修改
      if (row) {
        this.trademark.logName = row.tmName;
        this.trademark.logUrl = row.logoUrl;
        this.logId = row.id;
        this.isShowDialog = true;
        this.title = "修改";
      } else {
        // 否则是添加
        this.isShowDialog = true;
        this.title = "添加";
      }
    },

    // 清空所有数据
    cleardate() {
      this.title = "";
      this.trademark.logName = "";
      this.trademark.logUrl = "";
      this.logId = null;
    },

    // 取消按钮的回调 清空所有的数据
    deletetrademark() {
      this.isShowDialog = false;
      this.cleardate();
    },

    // 点击保存
    async saveTrademark() {
      // 先进行统一的表单验证
      this.$refs.ruleForm.validate(async valid => {
        if (valid) {
          // 验证通过 且存在id的话 就是修改
          if (this.logId) {
            const newTrademark = {
              tmName: this.trademark.logName,
              logoUrl: this.trademark.logUrl,
              id: this.logId
            };
            // 发起修改请求
            await updateTrademarkApi(newTrademark);
            this.$message.success("保存成功");
            this.isShowDialog = false;
            this.getPageList();
          } else {
            // 验证通过 不存在id的话 就是添加
            await saveTrademarkApi(
              this.trademark.logName,
              this.trademark.logUrl
            );
            this.$message.success("保存成功");
            this.isShowDialog = false;
            this.getPageList();
          }
        }
      });
    },

    // 点击删除
    async removeTrademark(id) {
      await removeTrademarkApi(id);
      this.$message.success("删除成功");
      if (this.pagelist.length <= 1) {
        this.page -= 1;
      }
      this.getPageList();
    },

    //图片的上传
    handleAvatarSuccess(res, file) {
      // this.logUrl = URL.createObjectURL(file.raw);
      // 上传成功 显示图片
      this.trademark.logUrl = res.data;

      // 清除表单校验错误信息
      this.$refs.ruleForm.clearValidate("logUrl");
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === "image/jpg" || file.type === "image/png";
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error("上传头像图片只能是 JPG 或者 PNG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return isJPG && isLt2M;
    }
  }
};
</script>

<style lang="scss" scoped>
.trademark {
  margin: 20px;
}
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
